﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
using SystemUpdatesCore.Server.Network;

namespace SystemUpdatesCore.Server
{
    /// <summary>
    /// 服务端-获取服务端下载
    /// </summary>
    public class ServerFiles : ServerBase
    {
        public ServerFiles() : base()
        {

            //下载完成
            networkClient.DownloadFileCompleted += OnDownloadFileCompleted;

            //下载进度
            networkClient.DownloadProgressChanged += OnDownloadProgressChanged;
        }

        /// <summary>
        /// 服务器配置
        /// </summary>
        public ServerVersionModel ServerVersion { get; private set; }


        /// <summary>
        /// 异步下载文件完成事件
        /// </summary>
        public event NetworkAsyncCompletedEventHandler? DownloadFileCompleted;
        /// <summary>
        /// 异步下载文件进度改变事件
        /// </summary>
        public event NetworkDownloadProgressChangedEventHandler? DownloadProgressChanged;

        /// <summary>
        /// 获取下载文件总字节数
        /// </summary>
        /// <param name="version"></param>
        /// <returns></returns>
        public long DownloadFileSizes(List<UpdateFileModel> fileNames)
        {
            long totalFileSize = 0;
            foreach (var file in fileNames)
            {
                totalFileSize += file.FileSize;
            }
            return totalFileSize;
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="serverVersion"></param>
        /// <returns></returns>
        public Task DownloadFilesTaskAsync(ServerVersionModel serverVersion, string? downloadPath = null)
        {
            ServerVersion = serverVersion;
            return DownloadFilesTaskAsync(ServerVersion.DownUrls, ServerVersion.UpdateFiles, downloadPath);
        }


        async Task DownloadFilesTaskAsync(List<string> address, List<UpdateFileModel> fileNames, string? downloadPath = null)
        {
            string? url = null;
            Exception error = null;
            while (address.Count > 0)
            {
                if (url == null)
                    url = address[0];

                if (url == null)
                {
                    DownloadFileCompleted?.Invoke(networkClient, new NetworkAsyncCompletedEventArgs(error, true, null));
                    return;
                }

                try
                {
                    await DownloadFilesTaskAsync(url, fileNames, downloadPath);
                    return;
                }
                catch (Exception ex)
                {
                    //如果出现错误，则换下个URL重新下载
                    address.Remove(url);
                    url = null;
                    error = ex;
                }
            };
        }


        async Task DownloadFilesTaskAsync(string url, List<UpdateFileModel> fileNames, string? downloadPath = null)
        {
            ResetDownloadFile();

            totalBytesToReceive = DownloadFileSizes(fileNames);
            Debug.WriteLine($"总文件大小{totalBytesToReceive}");
            //下载所有文件
            foreach (var file in fileNames)
            {
                progressFileCount++;
                downloadFileName = file;
                await networkClient.DownloadFileTaskAsync(url + file.DownUrl, Path.Combine(downloadPath ?? FilePath, file.FileName));
                //task.Wait();
            }

            //var changed = new NetworkDownloadProgressChangedEventArgs(100, null, bytesReceived, totalBytesToReceive);
            //DownloadProgressChanged?.Invoke(null, changed);

            return;
        }

        int progressPercentage = 0;//进度百分比
        long bytesReceived = 0;//已接收字节
        long totalBytesToReceive;//要接收的字节总数
        int progressFileCount = 0;//下载文件数
        UpdateFileModel downloadFileName = null;//当时下载的文件名

        /// <summary>
        /// 重置下载
        /// </summary>
        void ResetDownloadFile()
        {
            progressPercentage = 0;//进度百分比
            bytesReceived = 0;//已接收字节
            totalBytesToReceive = 0;//要接收的字节总数
            progressFileCount = 0;//下载文件数
            downloadFileName = null;//当时下载的文件名
        }

        /// <summary>
        /// 下载进度变更
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnDownloadProgressChanged(object sender, NetworkDownloadProgressChangedEventArgs e)
        {
            //Debug.WriteLine($"下载{bytesReceived}");
            bytesReceived += e.BytesReceived;
            //e TotalBytesToReceive 
            int progress = (int)(bytesReceived * 100 / totalBytesToReceive);
            if (progress > progressPercentage)
            {
                //if (progress >= 99)
                //    progress = 99;
                progressPercentage = progress;
                var changed = new NetworkDownloadProgressChangedEventArgs(progressPercentage, null, bytesReceived, totalBytesToReceive);
                DownloadProgressChanged?.Invoke(sender, changed);
                Debug.WriteLine($"下载进度：{changed.ProgressPercentage} %");
            }
        }

        /// <summary>
        /// 下载完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnDownloadFileCompleted(object? sender, AsyncCompletedEventArgs e)
        {
            var networkAsyncCompletedEventArgs = new NetworkAsyncCompletedEventArgs(
                progressFileCount,
                ServerVersion.UpdateFiles.Count,
                e.Error,
                e.Cancelled,
                e.UserState,

                downloadFileName
                );
            DownloadFileCompleted?.Invoke(sender, networkAsyncCompletedEventArgs);
        }



    }
}
